<template>
  <view class="user-container">
    
    <!-- 加载中提示 -->
    <view class="loading-container" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 内容区域 -->
    <scroll-view 
      class="content-scroll" 
      scroll-y 
      @scrolltolower="loadMorePosts"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="refresh"
      v-else
    >
      <!-- 用户信息卡片 -->
      <view class="user-card" v-if="userInfo">
        <view class="user-header">
          <image class="avatar" :src="userInfo.avatar" mode="aspectFill" />
          <view class="user-name">{{ userInfo.nickname }}</view>
          <view class="user-bio">{{ userInfo.bio }}</view>
          
          <!-- 添加好友/聊天按钮 -->
          <view 
            class="friend-btn" 
            :class="{ active: userInfo.isFriend }"
            @click="userInfo.isFriend ? goToChat() : showAddFriendModal()"
          >
            <view class="btn-icon">{{ userInfo.isFriend ? '💬' : '👋' }}</view>
            <view class="btn-text">{{ userInfo.isFriend ? '聊天' : '添加好友' }}</view>
          </view>
        </view>
        
        <!-- 用户数据统计 -->
        <view class="user-stats">
          <view class="stat-item">
            <view class="stat-value">{{ userInfo.postsCount }}</view>
            <view class="stat-label">动态</view>
          </view>
          <view class="stat-item">
            <view class="stat-value">{{ userInfo.followersCount }}</view>
            <view class="stat-label">粉丝</view>
          </view>
          <view class="stat-item">
            <view class="stat-value">{{ userInfo.followingCount }}</view>
            <view class="stat-label">关注</view>
          </view>
        </view>
        
        <!-- 用户简介 -->
        <view class="user-introduction">
          <text>热爱校园生活，分享校园趣事</text>
        </view>
      </view>
      
      <!-- 动态列表标题 -->
      <view class="section-title">
        <text>Ta的动态</text>
      </view>
      
      <!-- 动态列表 -->
      <view class="post-list" v-if="userPosts.length > 0">
        <post-item 
          v-for="post in userPosts" 
          :key="post.id" 
          :post="post"
          @like="handlePostLike"
        />
        
        <!-- 底部加载状态 -->
        <view class="list-footer" v-if="userPosts.length > 0">
          <text v-if="postsLoading">加载中...</text>
          <text v-else-if="!postsHasMore">没有更多动态了</text>
          <text v-else @click="loadMorePosts">点击加载更多</text>
        </view>
      </view>
      
      <!-- 空动态提示 -->
      <view class="empty-posts" v-else-if="!postsLoading">
        <text>暂无动态</text>
      </view>
    </scroll-view>
    
    <!-- 添加好友弹窗 -->
    <view class="add-friend-modal" v-if="showModal">
      <view class="modal-mask" @click="hideAddFriendModal"></view>
      <view class="modal-content">
        <view class="modal-title">添加好友</view>
        <view class="modal-body">
          <view class="input-label">附言</view>
          <textarea 
            class="message-input" 
            v-model="friendMessage" 
            placeholder="请输入附言消息..." 
            maxlength="50"
            auto-height
          />
          <view class="word-count">{{ friendMessage.length }}/50</view>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="hideAddFriendModal">取消</button>
          <button class="confirm-btn" @click="addFriend">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import PostItem from '../../components/community/PostItem.vue';

const store = useStore();

// 获取页面参数
const userId = ref(null);
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.id) {
    userId.value = options.id;
    fetchUserInfo();
    fetchUserPosts(true);
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
    setTimeout(() => {
      goBack();
    }, 1500);
  }
});

// 用户信息
const userInfo = computed(() => store.getters['community/userInfo']);

// 用户动态列表
const userPosts = computed(() => store.getters['community/userPosts']);

// 加载状态
const loading = computed(() => store.getters['community/loading'].userInfo);
const postsLoading = computed(() => store.getters['community/loading'].userPosts);

// 是否有更多动态
const postsHasMore = computed(() => store.getters['community/pagination'].hasMore);

// 是否正在刷新
const refreshing = ref(false);

// 添加好友弹窗状态
const showModal = ref(false);
const friendMessage = ref('');

// 获取用户信息
const fetchUserInfo = async () => {
  if (!userId.value) return;
  
  try {
    await store.dispatch('community/fetchUserInfo', userId.value);
  } catch (error) {
    console.error('获取用户信息失败', error);
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    });
  }
};

// 获取用户动态列表
const fetchUserPosts = async (refresh = false) => {
  if (!userId.value) return;
  
  try {
    await store.dispatch('community/fetchUserPosts', {
      userId: userId.value,
      refresh
    });
  } catch (error) {
    console.error('获取用户动态列表失败', error);
  }
};

// 刷新
const refresh = async () => {
  refreshing.value = true;
  await fetchUserInfo();
  await fetchUserPosts(true);
  refreshing.value = false;
};

// 加载更多动态
const loadMorePosts = async () => {
  if (postsLoading.value || !postsHasMore.value) return;
  await fetchUserPosts();
};

// 关注/取消关注
const handleFollow = async () => {
  if (!userInfo.value) return;
  
  const isFollow = !userInfo.value.isFollowed;
  
  try {
    await store.dispatch('community/followUser', {
      userId: userInfo.value.id,
      isFollow
    });
    
    uni.showToast({
      title: isFollow ? '关注成功' : '已取消关注',
      icon: 'success'
    });
  } catch (error) {
    console.error('关注操作失败', error);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 处理动态点赞
const handlePostLike = async (data) => {
  // 无需额外处理，store中已更新状态
};

// 显示添加好友弹窗
const showAddFriendModal = () => {
  showModal.value = true;
};

// 隐藏添加好友弹窗
const hideAddFriendModal = () => {
  showModal.value = false;
  friendMessage.value = '';
};

// 添加好友
const addFriend = async () => {
  if (!userInfo.value) return;
  
  try {
    const result = await store.dispatch('community/addFriend', {
      userId: userInfo.value.id,
      message: friendMessage.value
    });
    
    if (result) {
      uni.showToast({
        title: '好友申请已发送',
        icon: 'success'
      });
      
      hideAddFriendModal();
    } else {
      uni.showToast({
        title: '申请失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('添加好友失败', error);
    uni.showToast({
      title: '申请失败，请重试',
      icon: 'none'
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 前往聊天页面
const goToChat = () => {
  if (!userId.value) return;
  
  uni.navigateTo({
    url: `/pages/chat/message?userId=${userId.value}&nickname=${encodeURIComponent(userInfo.value?.nickname || '')}`
  });
};
</script>

<style lang="scss" scoped>
.user-container {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  background-color: #f5f5f5;
  
  /* 顶部导航栏已移除 */
  
  .loading-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .loading-text {
      font-size: 14px;
      color: #999999;
    }
  }
  
  .content-scroll {
    flex: 1;
    height: 0;
    
    .user-card {
      margin: 16px;
      background-color: #ffffff;
      border-radius: 20px;
      overflow: hidden;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
      
      .user-header {
        padding: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        
        .avatar {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          margin-bottom: 12px;
        }
        
        .user-name {
          font-size: 18px;
          font-weight: 600;
          color: #333333;
          margin-bottom: 6px;
        }
        
        .user-bio {
          font-size: 14px;
          color: #666666;
          text-align: center;
          margin-bottom: 16px;
        }
        
        .friend-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 8px 20px;
          font-size: 15px;
          color: #007aff;
          background-color: rgba(0, 122, 255, 0.1);
          border-radius: 22px;
          box-shadow: 0 2px 8px rgba(0, 122, 255, 0.15);
          
          .btn-icon {
            font-size: 16px;
            margin-right: 6px;
          }
          
          .btn-text {
            font-size: 15px;
          }
          
          &.active {
            color: #ffffff;
            background-color: #007aff;
          }
        }
      }
      
      .user-stats {
        display: flex;
        border-top: 1px solid #f5f5f5;
        
        .stat-item {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 12px 0;
          
          .stat-value {
            font-size: 16px;
            font-weight: 600;
            color: #333333;
            margin-bottom: 2px;
          }
          
          .stat-label {
            font-size: 12px;
            color: #999999;
          }
        }
      }
      
      .user-introduction {
        padding: 14px 20px;
        background-color: #f8f8f8;
        text-align: center;
        border-top: 1px solid #f0f0f0;
        
        text {
          font-size: 14px;
          color: #666666;
          line-height: 1.5;
        }
      }
    }
    
    .section-title {
      padding: 20px 16px 12px;
      font-size: 17px;
      font-weight: 600;
      color: #333333;
    }
    
    .post-list {
      padding: 0 16px;
      
      .list-footer {
        text-align: center;
        padding: 16px 0;
        font-size: 14px;
        color: #999999;
      }
    }
    
    .empty-posts {
      padding: 40px 0;
      text-align: center;
      font-size: 14px;
      color: #999999;
      background-color: #ffffff;
      margin: 0 16px;
      border-radius: 20px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }
  }
  
  .add-friend-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    
    .modal-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
    }
    
    .modal-content {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 80%;
      background-color: #ffffff;
      border-radius: 8px;
      overflow: hidden;
      
      .modal-title {
        padding: 16px;
        text-align: center;
        font-size: 16px;
        font-weight: 500;
        color: #333333;
        border-bottom: 1px solid #f5f5f5;
      }
      
      .modal-body {
        padding: 16px;
        position: relative;
        
        .input-label {
          font-size: 14px;
          color: #666666;
          margin-bottom: 8px;
        }
        
        .message-input {
          width: 100%;
          min-height: 80px;
          font-size: 14px;
          color: #333333;
          background-color: #f8f8f8;
          border-radius: 4px;
          padding: 8px;
        }
        
        .word-count {
          position: absolute;
          right: 16px;
          bottom: 16px;
          font-size: 12px;
          color: #999999;
        }
      }
      
      .modal-footer {
        display: flex;
        border-top: 1px solid #f5f5f5;
        
        button {
          flex: 1;
          height: 44px;
          line-height: 44px;
          text-align: center;
          font-size: 14px;
          border-radius: 0;
          
          &.cancel-btn {
            color: #666666;
            background-color: #ffffff;
          }
          
          &.confirm-btn {
            color: #ffffff;
            background-color: #007aff;
          }
        }
      }
    }
  }
}
</style>
